package com.reform.service.impl;

import com.alibaba.fastjson.JSON;
import com.reform.config.JwtTokenUtil;
import com.reform.pojo.common.FileInfo;
import com.reform.mapper.FileMapper;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.IFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.UUIDUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-07-27
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileInfo> implements IFileService {


    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @Override
    public Result fileUpload(HttpServletRequest request, MultipartFile[] files) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.failure(ResultCode.USER_AUTH_Login_LAPSE);
        }
        String gh = jwtTokenUtil.getGHFromToken(token);
        if (files == null || files.length == 0) {
            return Result.failure(ResultCode.PARAM_IS_MISSING);
        }
        List<Map<String, String>> resList = new ArrayList<>();
        for (MultipartFile file : files) {
            Map<String, String> map = new HashMap<>();
            String originalFileName = file.getOriginalFilename();
            String uuid = UUIDUtils.getUUID();
            assert originalFileName != null;
            //获取文件后缀名
            String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            //生成随机文件名
            String fileName = uuid + "." + suffix;
            //根据文件后缀名生成文件夹
            String pathname = uploadFolder + gh+ "/"  + suffix + "/" + fileName;
            java.io.File dest = new java.io.File(pathname);
            if (!dest.getParentFile().exists()) {
                boolean mkdirs = dest.getParentFile().mkdirs();
                if (!mkdirs) {
                    return Result.failure(ResultCode.SYSTEM_ERROR);
                }
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
                map.put("fileName", originalFileName + "添加失败");
            }
            map.put("filePath", pathname);
            map.put("fileName", originalFileName);
            resList.add(map);
        }
        return Result.failure(ResultCode.SUCCESS, resList);
    }


    @Override
    public Result fileDelete(String fileNames) {
        List<FileInfo> fileList = JSON.parseArray(fileNames, FileInfo.class);
        for (FileInfo file : fileList) {
            String fileName = file.getName();
            //获取文件后缀名
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            try {
                Path path = Paths.get(uploadFolder + suffix + "/" + fileName);
                if (!FileSystemUtils.deleteRecursively(path)) {
                    return Result.failure(ResultCode.PARAM_IS_WRONG, fileName + " 删除失败");
                }
            } catch (InvalidPathException e2) {
                return Result.failure(ResultCode.PARAM_IS_WRONG, fileName + " 删除失败");
            } catch (IOException e) {
                e.printStackTrace();
                return Result.failure(ResultCode.PARAM_IS_WRONG, fileName + " 删除失败 ");
            }
        }
        return Result.success(ResultCode.SUCCESS);
    }

    @Override
    public Result fileDownload(HttpServletResponse response, String fileUrl, String fileName) {
        try {
            //获取文件输入流
            FileInputStream is = new FileInputStream(new File(fileUrl));
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream os = response.getOutputStream();
            org.apache.tomcat.util.http.fileupload.IOUtils.copy(is, os);
            org.apache.tomcat.util.http.fileupload.IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            return Result.success(ResultCode.SUCCESS);
        } catch (Exception e) {
            log.error("文件下载出现异常", e);
            return Result.failure(ResultCode.FAILURE);
        }
    }
}
